<?php
/**
 * Created by PhpStorm.
 * User: jucai002
 * Date: 2019/1/23
 * Time: 16:54
 */

namespace app\modules\admin\controllers;


use app\models\Channel;

class ChannelController extends DefaultController
{
    /**
     * @return string
     * 渠道列表
     */
    public function actionIndex()
    {
        //渠道链接地址
        $ch = Channel::find()->asArray()->all();

        return $this->render('index', ['head' => $this->Index(), 'end' => $this->End(), 'data' => $ch]);
    }

    /**
     * 渠道添加
     */
    public function actionAdd()
    {
        $name = \Yii::$app->request->post('title', false);
        if (!empty($name)) {
            $ch = new Channel();
            $ch->name = $name;
            $ch->save(false);
            //处理渠道链接
            $id = \Yii::$app->db->getLastInsertID();
            $url = $this->URL."?channel=".$id;
            $ch = Channel::findOne($id);
            $ch->url = $url;
            $ch->save();
        }
        $this->redirect(\Yii::$app->urlManager->createUrl('admin/channel/index'));
    }

    public function actionSave()
    {

        if( empty(\Yii::$app->request->post()))
        {
            $id = \Yii::$app->request->get('id',0);
            $ch = Channel::findOne($id);
            if(empty($ch)) $this->redirect(\Yii::$app->urlManager->createUrl('admin/channel/index'));
            return $this->render('save', ['head' => $this->Index(), 'end' => $this->End(), 'data' => $ch]);
        }else{
            $id = \Yii::$app->request->post('id',0);
            $name = \Yii::$app->request->post('title','');
            $ch = Channel::findOne($id);
            if(empty($ch)) $this->redirect(\Yii::$app->urlManager->createUrl('admin/channel/index'));
            $ch->name = $name;
            $ch->save();
            $this->redirect(\Yii::$app->urlManager->createUrl('admin/channel/index'));
        }
    }

}